#include <stdio.h>
#include <signal.h>

#define TIMEOUT     5       // 超时时间
#define MAXTRIES    5       // 最大尝试次数
#define LINESIZE    100
#define BELL        '007'
#define TRUE        1
#define FALSE       0

// 判断超时是否已经发生的标志
static int time_out;

static char inputline[LINESIZE];
char* quickreply(char* prompt);

main()
{
    printf("%s\n", quickreply("Input"));
}

char* quickreply(char* prompt)
{
    int (*was)(), catch(), ntries;
    char* answer;

    was = signal(SIGALRM, catch); // 设定捕捉SIGALRM的关联并保存原有关联

    for(ntries = 0; ntries <MAXTRIES; ntries++)
    {
        time_out = FALSE;
        printf("%s\n", prompt);

        // 设置定时器
        alarm(TIMEOUT);

        // 获取输入
        answer = gets(inputline);

        // 关闭定时器
        alarm(0);

        if(!time_out)
            break;
    }

    signal(SIGALRM, was); // 恢复原有的SIGALRM关联

    return (time_out?((char*)0):answer);
}

catch()
{
    time_out = TRUE; // 设定超时标志
    printf("\nTIME OUT\n");
    putchar(BELL); // 响铃警告
}